package com.lovo.shirodemo.shiro;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lovo.shirodemo.result.ResultCode;
import com.lovo.shirodemo.result.ResultVO;
import com.lovo.shirodemo.util.WebUtil;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class RestAuthorizationFilter  extends PermissionsAuthorizationFilter {
    @Override
    protected boolean pathsMatch(String path, ServletRequest request) {
        String requestURI = this.getPathWithinApplication(request);
        String[] strings = path.split("==");
        if (strings.length <= 1) {
            // 普通的 URL, 正常处理
            return this.pathsMatch(strings[0], requestURI);
        } else {
            // 获取当前请求的 http method.
            String httpMethod = WebUtils.toHttp(request).getMethod().toUpperCase();
            // 匹配当前请求的 http method 与 过滤器链中的的是否一致
            return httpMethod.equals(strings[1].toUpperCase()) && this.pathsMatch(strings[0], requestURI);
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        Subject subject = getSubject(request, response);
        // 如果未登录
        if (subject.getPrincipal() == null) {
            WebUtil.writeJson(ResultVO.fail(ResultCode.USER_AUTHENTICATION_ERROR),response);
        } else {
            WebUtil.writeJson(ResultVO.fail(ResultCode.USER_AUTHORIZATION_ERROR),response);
        }
        return false;
    }


}
